//
//  RegisterViewController.m
//  customer
//
//  Created by 往返网络 on 17/4/17.
//  Copyright © 2017年 com. All rights reserved.
//

#import "RegisterViewController.h" //注册界面
#import "PublicMethod.h"
//定义获取验证码URL
#define URL_GETMESSAGECODE [NSString stringWithFormat:@"%@/Appcustomernew/Register/getCode?type=get",BASE_URL]
//定义注册URL
#define URL_REGIST [NSString stringWithFormat:@"%@/Appcustomernew/Register/register?type=get",BASE_URL]


@interface RegisterViewController ()<UITextFieldDelegate>
//开辟多线程定时器，在后台执行，比NSTimer更自然
@property (nonatomic,strong) dispatch_source_t timer;

@property (nonatomic,strong)AFHTTPSessionManager* manger;
@end

@implementation RegisterViewController
{

    UIImageView * backimg; //背景图
    
    UILabel * titlelabel; // 标题
    
    UITextField * phonetf;  //手机号
    
    UITextField * messagetf;  //短信验证码
    
    UIButton * messbtn; // 获取验证码
    
    UITextField * passwordtf;   //密码
    
    UIButton * zhucebtn;  //注册
    
    UIButton * enterloginbtn; //去登陆

  

}

- (void)loadTimer{
    
    
    __block NSInteger time = 59; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮的样式
                [messbtn setTitle:@"重新发送" forState:UIControlStateNormal];
                
                [messbtn setTitleColor:[UIColor colorWithRed:47/255.0 green:147/255.0 blue:258/255.0 alpha:1] forState:UIControlStateNormal];
                
                [messbtn setTitleColor:COLORRGBA(174, 174, 173, 1) forState:UIControlStateNormal];

                messbtn.userInteractionEnabled = YES;
                
            });
            
        }else{
            
            int seconds = time % 60;
            dispatch_async(dispatch_get_main_queue(), ^{
                
                //设置按钮显示读秒效果 %2d秒后重新发送
                [messbtn setTitle:[NSString stringWithFormat:@"已发送(%2ds)", seconds] forState:UIControlStateNormal];
//                [messbtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
                
                messbtn.layer.borderWidth = 0;
                
                [messbtn setTitleColor:COLORRGBA(174, 174, 173, 1) forState:UIControlStateNormal];

                messbtn.userInteractionEnabled = NO;
            });
            time--;
            
        }
    });
    
    dispatch_resume(_timer);
    
    
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self createUI];
    
    // Do any additional setup after loading the view.
}


- (void)createUI{

    
    //适配字体大小,圆角大小
    
    float fontsie = 15;
    
    float cornersize = 20;
    
    fontsie = SCREEN_H < 667 ? 13 :  17;
    
    cornersize = SCREEN_H < 667 ? 18 : 22 ;
    
    
    if (SCREEN_H == 667) {
        
        fontsie = 15;
        
        cornersize = 20;
        
    }

    
    self.view.backgroundColor = [UIColor whiteColor];
    
    


    titlelabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 20, SCREEN_W, 44)];
    
    titlelabel.textAlignment = NSTextAlignmentCenter;
    
    
    titlelabel.font = [UIFont systemFontOfSize:fontsie+2];
    
    [self.view addSubview:titlelabel];
    
    
    backimg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 750.0/750*SCREEN_W, 422.0/1334*SCREEN_H)];
    
    backimg.image = [UIImage imageNamed:@"registback_.png"];
    
    [self.view addSubview:backimg];
    
    //手机号。。密码 输入框创建
    
    phonetf = [[UITextField alloc]initWithFrame:CGRectMake(65.0/W_BASE*SCREEN_W, 346.0/H_BASE*SCREEN_H, 605.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];

    phonetf.layer.borderWidth = 1;
    
    phonetf.font = [UIFont systemFontOfSize:fontsie];
    
    
    //设置tf的缩紧，靠右缩紧，给tf加一个leftview
    
    UIView * leftview  = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    
    phonetf.leftView = leftview;
    
    phonetf.leftViewMode = UITextFieldViewModeAlways;
    
    phonetf.layer.borderColor = [[UIColor colorWithRed:239.0/255 green:239.0/255 blue:239.0/255 alpha:1]CGColor];
    
    phonetf.placeholder = @"手机号";
    
    phonetf.clearButtonMode = UITextFieldViewModeAlways;
    
    phonetf.layer.cornerRadius = cornersize;
    
    [self.view addSubview:phonetf];
    
    messagetf = [[UITextField alloc]initWithFrame:CGRectMake(65.0/W_BASE*SCREEN_W, CGRectGetMaxY(phonetf.frame)+20.0/H_BASE*SCREEN_H, 605.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    
    messagetf.layer.borderWidth = 1;
    
    UIView * leftview1  = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    
    messagetf.leftView = leftview1;
    
    messagetf.font = [UIFont systemFontOfSize:fontsie];
    
    messagetf.leftViewMode = UITextFieldViewModeAlways;
    
    messagetf.layer.borderColor = [[UIColor colorWithRed:239.0/255 green:239.0/255 blue:239.0/255 alpha:1]CGColor];
    
    messagetf.placeholder = @"短信验证码";
    
//    messagetf.clearButtonMode = UITextFieldViewModeAlways;
    
    messagetf.layer.cornerRadius = cornersize;
    
    [self.view addSubview:messagetf];
    
    messbtn = [[UIButton alloc]initWithFrame:CGRectMake(CGRectGetMaxX(messagetf.frame)- 171.0/W_BASE*SCREEN_W, CGRectGetMinY(messagetf.frame)+10.0/H_BASE*SCREEN_H, 150.0/W_BASE*SCREEN_W, 60.0/H_BASE*SCREEN_H)];
    
    messbtn.layer.cornerRadius = 2;
    
    messbtn.clipsToBounds = YES;
    
    [messbtn setTitleColor:COLORRGBA(174, 174, 173, 1) forState:UIControlStateNormal];
    
    messbtn.titleLabel.font = [UIFont systemFontOfSize:fontsie - 3];
    
    messbtn.backgroundColor = COLORRGBA(238, 240, 239, 1);
    
    [self.view addSubview:messbtn];
    
    [messbtn setTitle:@"获取验证码" forState:UIControlStateNormal];
    
    messbtn.tag = 1000;
    
    messbtn.userInteractionEnabled = NO;
    
    [messbtn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    passwordtf = [[UITextField alloc]initWithFrame:CGRectMake(65.0/W_BASE*SCREEN_W, CGRectGetMaxY(messagetf.frame)+20.0/H_BASE*SCREEN_H, 605.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    
    passwordtf.layer.borderWidth = 1;
    
    UIView * leftview2  = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    
    passwordtf.leftView = leftview2;
    
    passwordtf.font = [UIFont systemFontOfSize:fontsie];
    
    passwordtf.leftViewMode = UITextFieldViewModeAlways;
    
    passwordtf.layer.borderColor = [[UIColor colorWithRed:239.0/255 green:239.0/255 blue:239.0/255 alpha:1]CGColor];
    
    passwordtf.placeholder = @"密码";
    
    passwordtf.clearButtonMode = UITextFieldViewModeAlways;
    
    
    passwordtf.layer.cornerRadius = cornersize;
    
    [self.view addSubview:passwordtf];

    
    zhucebtn = [[UIButton alloc]initWithFrame:CGRectMake(65.0/W_BASE*SCREEN_W, CGRectGetMaxY(passwordtf.frame)+20.0/H_BASE*SCREEN_H, 605.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H)];
    

    [zhucebtn setTitle:@"注册" forState:UIControlStateNormal];
    
    zhucebtn.userInteractionEnabled = NO;
    
    zhucebtn.tag = 2000;
    
    zhucebtn.layer.cornerRadius = cornersize;
    
    zhucebtn.clipsToBounds = YES;
    
    zhucebtn.titleLabel.font = [UIFont systemFontOfSize:fontsie];
    

//    [zhucebtn setBackgroundColor:COLORRGBA(38, 146, 255, 1)];
    
    zhucebtn.backgroundColor = [UIColor colorWithRed:47.0/255 green:148.0/255 blue:251.0/255 alpha:0.5];

    [zhucebtn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:zhucebtn];
    
    
    enterloginbtn = [[UIButton alloc]initWithFrame:CGRectMake(65.0/W_BASE*SCREEN_W, CGRectGetMaxY(zhucebtn.frame)+20.0/H_BASE*SCREEN_H, 605.0/W_BASE*SCREEN_W, 30.0/H_BASE*SCREEN_H)];
    
    [enterloginbtn setTitle:@"已有账号？去登陆" forState:UIControlStateNormal];
    
    enterloginbtn.titleLabel.font = [UIFont systemFontOfSize:fontsie];
    
    [enterloginbtn setTitleColor:COLORRGBA(102, 102, 102, 1) forState:UIControlStateNormal];
    
    enterloginbtn.tag = 3000; //
    
    [enterloginbtn addTarget:self action:@selector(enterClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view addSubview:enterloginbtn];
    
    passwordtf.secureTextEntry = YES;
    
    passwordtf.backgroundColor = [UIColor whiteColor];
    
    messagetf.backgroundColor = [UIColor whiteColor];
    
    phonetf.backgroundColor = [UIColor whiteColor];
    
    passwordtf.delegate = self;
    
    messagetf.delegate = self;
    
    phonetf.delegate = self;


}

#pragma mark - -- Action - -- - - -

- (void)enterClick:(UIButton *)btn{

   //
    
    NSInteger tag = btn.tag;
    
    switch (tag) {
            
        case 1000:
            //短信验证码
        {
        
            NSLog(@"获取短信验证码");
            
            [self getYanzhengString];
            
            
            break;
            
        }
            case 2000:
            
            //注册
        {
        
            NSLog(@"注册");
            
            
            //注册成功提示
            if (![PublicMethod isValidateTel:phonetf.text])
                
            {
                
                ALERT(@"提示", @"手机号格式错误", nil, @"确认", nil);
                
                return;
                
            }

            if (!(messagetf.text.length == 6)) {
                
                ALERT(@"提示", @"验证码位数不对", nil, @"确认", nil);

                return;
                
            }
            
            if (!(passwordtf.text.length == 6)) {
                
                ALERT(@"提示", @"密码位数不对", nil, @"确认", nil);
                
                return;
                
            }
            
            
            [self   beginRegister];
            
            
            
            break;
        
        }
            case 3000:
            
            //去登陆页面
        {
        
            NSLog(@"进入登录页面");
            
            [self dismissViewControllerAnimated:YES completion:nil];
            
            
            break;
        }
            
            
        default:
            
            break;
            
    }


}

#pragma mark  - -- - - 获取验证码- -- - - - - -

- (void)getYanzhengString{

    //字符串反转之后，再发送出去 phonenum --- 反转 －－－＊2 －－－ 转化为a-z
    
    NSMutableString *s = [NSMutableString string];
    
    for (NSUInteger i = phonetf.text.length; i>0; i--) {
        
        [s appendString:[phonetf.text substringWithRange:NSMakeRange(i-1, 1)]];
        
    }
    
    NSInteger s1 = [s integerValue]*2;
    
    NSString * s2 = [NSString stringWithFormat:@"%ld",s1];
    
    NSLog(@"s2 %@",s2);
    
    NSArray * arr = @[@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j"];
    
    NSMutableString * endstring = [NSMutableString string];
    
    for (NSUInteger i = 0; i < s2.length; i++) {
        
     //截取1个字符串
     NSString * s3 =  [s2 substringWithRange:NSMakeRange(i, 1)];
        
     NSInteger loc = [s3 integerValue];
        
      // 转化为小写字母
    
     NSString * s4 = arr[loc];

    [endstring appendString:s4];
        
    
    }
    
    NSLog(@"endstring %@",endstring);
    
    NSString * url = [NSString stringWithFormat:@"%@&mobile=%@",URL_GETMESSAGECODE,endstring];
    
    NSLog(@"get 验证码 url %@",url);
    
    [self.manger GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        if (responseObject) {
            
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            NSInteger code = [dict[@"code"]integerValue];
            
            if (code == 0) {
                
                //获取验证码成功
                
                NSLog(@"get code ok");
                
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
                
                //发送短信
                [self loadTimer];
                
                
            }else{
            
                NSLog(@"get code no");

                ALERT(@"提示", dict[@"info"], self, @"确定", nil);

            }
            

        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        ALERT(@"提示", @"网络请求失败", self, @"确定", nil);
        
    }];
    


}


#pragma mark  - -- - - -  - - -- - 注册 - - - - -- - - -

- (void)beginRegister{


    UIImageView * im = [PublicMethod startAnimation];
    
    
    NSString * url = [NSString stringWithFormat:@"%@&mobile=%@&msgCode=%@&password=%@",URL_REGIST,phonetf.text,messagetf.text,passwordtf.text];
    
    NSLog(@"注册 url %@",url);
    
    [self.manger GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if (responseObject) {
            
            NSDictionary * dict = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            NSInteger code = [dict[@"code"]integerValue];
            
            if (code == 0) {
                
                //获取验证码成功
                
                [im stopAnimating];

                
                NSLog(@"get code ok");
                
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
                
                //回到登陆页面去登录
                [self dismissViewControllerAnimated:YES completion:nil];
                

                
                
            }else{
                
                [im stopAnimating];

                NSLog(@"get code no");
                
                ALERT(@"提示", dict[@"info"], self, @"确定", nil);
                

                
            }
            
            
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        [im stopAnimating];

        ALERT(@"提示", @"网络请求失败", self, @"确定", nil);
        
    }];
    
    







}


- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    
    
    //当手机号为11位的时候，获取验证码变色 ,只要有输入1位，注册按钮变色
    
    NSString * textstring = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    if (textstring.length >= 1) {
        
        
        [zhucebtn setBackgroundColor:COLORRGBA(38, 146, 255, 1)];

        zhucebtn.userInteractionEnabled = YES;

    }
    
    if (textstring.length >= 11 && textField == phonetf) {
        
        
        [messbtn setTitleColor:COLORRGBA(255, 102, 102, 1) forState:UIControlStateNormal];

        messbtn.layer.borderWidth = 1;
        
        messbtn.layer.borderColor = [COLORRGBA(255, 102, 102, 1)CGColor];
        
        messbtn.userInteractionEnabled  = YES;
        
        
    }

    
    return YES;
    
    
    
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{


    [self.view endEditing:YES];
    
    [self makeDownView];
       

}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField{

    
    //页面整体上移

    [self makeUPView];
    
    return YES;
    

}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{


    [self.view endEditing:YES];
    
    
    return YES;
    
}

#pragma mark - - -- - - 页面整体上移－ － － － －

- (void)makeUPView{
    
    [UIView animateWithDuration:0.5 animations:^{
        
        
        //显示注册标题
        
        titlelabel.text = @"注册";
        
    
        CGRect rect1 = CGRectMake(0, -422.0/1334*SCREEN_H, 750.0/750*SCREEN_W, 422.0/1334*SCREEN_H);
        
        backimg.frame = rect1;
        
        
        CGRect rect2 = CGRectMake(65.0/W_BASE*SCREEN_W, CGRectGetMaxY(titlelabel.frame)+20.0/H_BASE*SCREEN_H, 605.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H);
        
        phonetf.frame = rect2;
        
        CGRect rect3 = CGRectMake(65.0/W_BASE*SCREEN_W, CGRectGetMaxY(phonetf.frame)+20.0/H_BASE*SCREEN_H, 605.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H);
        
        messagetf.frame = rect3;
        
        CGRect  rect4 = CGRectMake(65.0/W_BASE*SCREEN_W, CGRectGetMaxY(messagetf.frame)+20.0/H_BASE*SCREEN_H, 605.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H);
        
        passwordtf.frame = rect4;
        
        
        CGRect rect5 = CGRectMake(65.0/W_BASE*SCREEN_W, CGRectGetMaxY(passwordtf.frame)+20.0/H_BASE*SCREEN_H, 605.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H);
        
        zhucebtn.frame = rect5;
        
        
        CGRect rect6 = CGRectMake(65.0/W_BASE*SCREEN_W, CGRectGetMaxY(zhucebtn.frame)+20.0/H_BASE*SCREEN_H, 605.0/W_BASE*SCREEN_W, 30.0/H_BASE*SCREEN_H);
        
        enterloginbtn.frame = rect6;
        
        CGRect rect7 = CGRectMake(CGRectGetMaxX(messagetf.frame)- 171.0/W_BASE*SCREEN_W, CGRectGetMinY(messagetf.frame)+10.0/H_BASE*SCREEN_H, 150.0/W_BASE*SCREEN_W, 60.0/H_BASE*SCREEN_H);
        
        messbtn.frame = rect7;
        

        
        
    } completion:nil];
    
    
}

- (void)makeDownView{


    [UIView animateWithDuration:(0.5) animations:^{
        
        //隐藏注册标题
        
        titlelabel.text = @"";
        
     //背景图
        CGRect rect1 = CGRectMake(0, 0, 750.0/750*SCREEN_W, 422.0/1334*SCREEN_H);
        
        backimg.frame = rect1;
        
        //手机号
        CGRect rect2 = CGRectMake(65.0/W_BASE*SCREEN_W, 346.0/H_BASE*SCREEN_H, 605.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H);
        
        phonetf.frame = rect2;
        
        //短信验证
        CGRect rect3 = CGRectMake(65.0/W_BASE*SCREEN_W, CGRectGetMaxY(phonetf.frame)+20.0/H_BASE*SCREEN_H, 605.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H);
        
        messagetf.frame = rect3;
        
        CGRect  rect4 = CGRectMake(65.0/W_BASE*SCREEN_W, CGRectGetMaxY(messagetf.frame)+20.0/H_BASE*SCREEN_H, 605.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H);
        
        passwordtf.frame = rect4;
        
        
        CGRect rect5 = CGRectMake(65.0/W_BASE*SCREEN_W, CGRectGetMaxY(passwordtf.frame)+20.0/H_BASE*SCREEN_H, 605.0/W_BASE*SCREEN_W, 80.0/H_BASE*SCREEN_H);
        
        zhucebtn.frame = rect5;
        
        
        CGRect rect6 = CGRectMake(65.0/W_BASE*SCREEN_W, CGRectGetMaxY(zhucebtn.frame)+20.0/H_BASE*SCREEN_H, 605.0/W_BASE*SCREEN_W, 30.0/H_BASE*SCREEN_H);
        
        enterloginbtn.frame = rect6;
        
        CGRect rect7 = CGRectMake(CGRectGetMaxX(messagetf.frame)- 171.0/W_BASE*SCREEN_W, CGRectGetMinY(messagetf.frame)+10.0/H_BASE*SCREEN_H, 150.0/W_BASE*SCREEN_W, 60.0/H_BASE*SCREEN_H);
        
        messbtn.frame = rect7;
        

        
    } completion:nil];
    
    

}


- (AFHTTPSessionManager *)manger{


    if (!_manger) {
        
        _manger = [AFHTTPSessionManager manager];
        
        _manger.responseSerializer =  [AFHTTPResponseSerializer serializer];
        
        _manger.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", nil];
        
    }

    return _manger;

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
